<template>
  <div>
    <canvas class="box" ref="canvasRef" width="500" height="500" @click="handleClick"></canvas>
  </div>
  <button @click="checkOut">结算</button>
  <div v-show="checkedStatus.length > 0" v-for="item in checkedStatus" :key="checkedStatus.row">
    <span>第 {{ item.row }}排 </span>
    <span> {{ item.col }}座</span>
  </div>
</template>


<script setup >
import { onMounted, ref, watch } from 'vue';

const canvasRef = ref(null)
const rows = 10 //行
const cols = 10 //列
const seatSize = 40 //座位大小
const seatGap = 11 //座位间隔

// 二维数组
const seatStatus = ref(new Array(rows).fill(null).map(() => new Array(cols).fill(false)))
// console.log(seatStatus.value)

function drawSeats() {
  const canvas = canvasRef.value
  const ctx = canvas.getContext('2d')
  ctx.clearRect(0, 0, canvas.width, canvas.height)
  for (let row = 0; row < rows; row++) {
    for (let col = 0; col < cols; col++) {
      const x = col * (seatSize + seatGap)
      const y = row * (seatSize + seatGap)
      ctx.fillStyle = seatStatus.value[row][col] ? "#ff0000" : '#ccc'
      ctx.fillRect(x, y, seatSize, seatSize)
    }
  }
}

const handleClick = (event) => {
  // console.log('click', event)
  const canvas = canvasRef.value
  const rect = canvas.getBoundingClientRect()
  // 判断点击的位置是否在canvas内  //是否缩放
  const scaleX = canvas.width / rect.width
  const scaleY = canvas.height / rect.height
  // 获取x,y坐标 ，相对于canvas
  const x = (event.clientX - rect.left) * scaleX
  const y = (event.clientY - rect.top) * scaleY
  // console.log(x,y)

  // 计算点击的是第几行第几列
  const col = Math.floor(x / (seatSize + seatGap))
  const row = Math.floor(y / (seatSize + seatGap))
  // console.log(row,col)

  // 画一个红色的座位
  seatStatus.value[row][col] = !seatStatus.value[row][col]
  drawSeats()
}




const checkedStatus = ref([])


const checkOut = () => {
  checkedStatus.value = []
  for (let row = 0; row < rows; row++) {
    for (let col = 0; col < cols; col++) {
      // console.log(seatStatus.value[row][col])
      if (seatStatus.value[row][col]) {
        checkedStatus.value.push({ row: row + 1, col: col + 1 })
      }
    }
  }
}



onMounted(() => {
  drawSeats()
})

</script>


<style scoped>
.box {
  box-shadow: rgba(17, 22, 40, 0.15) 0 48px 100px 0;
}
</style>
